package club.vann.kafka.mock.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
import java.util.Set;

public class JSONUtil {
  private JSONUtil() {}

  /**
   * 根据Map创建对应的实例对象。
   *
   * @param map 参数信息
   * @param clazz 待实例化类型
   * @return 实例
   * @param <T> 实例类型
   */
  public static <T> T parse(Map<String, Object> map, Class<T> clazz) {
    if (map != null) {
      return JSON.parseObject(JSON.toJSONString(map), clazz);
    }
    return null;
  }

  public static Object getJSONValue(Object object, String key) {
    if (object == null) {
      return null;
    }
    if (object instanceof JSONObject jsonObject) {
      return getJSONValue(jsonObject, key);
    } else if (object instanceof JSONArray jsonArray) {
      return getJSONValue(jsonArray, key);
    }
    return null;
  }

  private static Object getJSONValue(JSONObject json, String key) {
    if (key == null) {
      return null;
    }
    Object value = null;
    Set<Map.Entry<String, Object>> entries = json.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
      String entryKey = entry.getKey();
      Object entryValue = entry.getValue();
      if (entryKey.equals(key)) {
        value = entryValue != null ? entryValue : "";
      } else {
        value = getJSONValue(entryValue, key);
      }

      if (value != null) {
        break;
      }
    }
    return value;
  }

  private static Object getJSONValue(JSONArray jsonArray, String key) {
    if (key == null) {
      return null;
    }
    Object value = null;

    for (Object object : jsonArray) {
      value = getJSONValue(object, key);
      if (value != null) {
        break;
      }
    }
    return value;
  }
}
